import datetime
from flask import Blueprint, render_template, request, session
from flask_login import login_required, current_user
from sqlalchemy import desc

from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Role, Dept
from applications.models import User, AdminLog
from applications.models import Article
import html
admin_article = Blueprint('adminArticle', __name__, url_prefix='/admin/article')


# 用户管理
@admin_article.get('/')
@authorize("admin:article:main")
def main():
    return render_template('admin/article/main.html')


# 表格数据
@admin_article.get('/data')
@authorize("admin:article:main")
def data():
    title = str_escape(request.args.get('title', type=str))
    filters = []

    if title:
        filters.append(Article.title.contains(title))
    # if name:
    #     filters.append(Article.rolename.contains(name))
    filters.append(Article.type.contains(1))
    Articles = Article.query.filter(*filters).layui_paginate()
    return table_api(
        data=[{
            'id': Article.article_id,
            'update_time': Article.update_time,
            'create_time': Article.create_time,
            'pub_time': Article.pub_time,
            'title': Article.title,
            'admin_id': Article.admin_id,
            'image': Article.image,
            'status': Article.status,
        } for Article in Articles.items],
        count=Articles.total)


@admin_article.get('/add')
@authorize("admin:article:add", log=True)
def add():
    roles = Role.query.all()

    return render_template('admin/article/add.html', roles=roles)


@admin_article.get('/edit/<int:id>')
@authorize("admin:article:edit", log=True)
def edit(id):
    article = curd.get_one_article_by_id(Article, id)

    article.content = html.unescape(article.content)

    return render_template('admin/article/edit.html', article=article)


@admin_article.post('/save')
@authorize("admin:article:save", log=True)
def save():
    req_json = request.get_json(force=True)
    title = str_escape(req_json.get('title'))
    content = str_escape(req_json.get('content'))
    type = 1
    status = str_escape(req_json.get('status'))
    if (status == 'on'):
        status = 1
    else:
        status = 2
    image = str_escape(req_json.get('image'))
    video = str_escape(req_json.get('video'))
    pub_time = str_escape(req_json.get('pub_time'))
    introduction = str_escape(req_json.get('introduction'))
    create_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    update_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    admin_id = session["_user_id"]
    article = Article(title=title, content=content, type=type, status=status, image=image,
                      video=video, pub_time=pub_time, introduction=introduction, create_time=create_time,
                      update_time=update_time,admin_id=admin_id)
    db.session.add(article)
    db.session.commit()
    return success_api(msg="增加成功")


@admin_article.put('/update')
@authorize("admin:article:edit", log=True)
def update():
    req_json = request.get_json(force=True)
    article_id = str_escape(req_json.get('article_id'))
    title = str_escape(req_json.get('title'))
    content = str_escape(req_json.get('content'))

    status = str_escape(req_json.get('status'))
    if (status == 'on'):
        status = 1
    else:
        status = 2
    image = str_escape(req_json.get('image'))
    video = str_escape(req_json.get('video'))
    pub_time = str_escape(req_json.get('pub_time'))
    introduction = str_escape(req_json.get('introduction'))
    update_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    data = {
        "title": title,
        "content": content,
        "status": status,
        "image": image,
        "video": video,
        "pub_time": pub_time,
        "update_time": update_time,
        'introduction': introduction
    }
    Article.query.filter_by(article_id=article_id).update(data)
    db.session.commit()
    return success_api(msg="更新成功")


@admin_article.delete('/remove/<int:id>')
@authorize("admin:article:remove", log=True)
def remove(id):
    r = Article.query.filter_by(article_id=id).delete()
    db.session.commit()
    if not r:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


@admin_article.delete('/batchRemove')
@authorize("admin:article:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        res = Article.query.filter_by(article_id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")
